package com.simdo.g768.Fragment;

import static com.simdo.g768.MainActivity.device;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.g768.Bean.UeidBean;
import com.simdo.g768.Adapter.ImsiAdapter;
import com.simdo.g768.Bean.GnbBean;
import com.simdo.g768.Bean.HistoryBean;
import com.simdo.g768.Bean.ImsiBean;
import com.simdo.g768.Bean.MyUeidBean;
import com.simdo.g768.Dialog.BulkOperationDialog;
import com.simdo.g768.Dialog.TraceDialog;
import com.simdo.g768.Listener.BeanClickListener;
import com.simdo.g768.MainActivity;
import com.simdo.g768.R;
import com.simdo.g768.Util.AppLog;
import com.simdo.g768.Util.GsonUtil;
import com.simdo.g768.Util.PrefUtil;
import com.simdo.g768.Util.Util;
import com.simdo.g768.ZApplication;

import java.util.ArrayList;
import java.util.List;

public class CatchChildFragment extends Fragment {

    Context mContext;
    private ImsiAdapter mImsiAdapter;
    private final List<ImsiBean> mImsiList = new ArrayList<>();
    public CatchChildFragment(Context context, List<ImsiBean> list) {
        this.mContext = context;
        this.mImsiList.addAll(list);
    }
    public CatchChildFragment() {
    }

    @SuppressLint("NotifyDataSetChanged")
    public void refreshListView() {
        this.mImsiList.clear();
        for (ImsiBean bean : MainActivity.getInstance().getImsiList()){
            if (bean.getImsi().contains(currentKey)) this.mImsiList.add(bean);
        }
        if (mImsiAdapter != null) mImsiAdapter.resetShowData();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppLog.I("CatchChildFragment onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        AppLog.I("CatchChildFragment onCreateView");

        View root = inflater.inflate(R.layout.child_pager_catch, container, false);

        initView(root);
        return root;
    }
    private String currentKey = "";
    private void initView(View root) {
        EditText mEtSearch = root.findViewById(R.id.et_search);
        mEtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void afterTextChanged(Editable s) {
                List<ImsiBean> mAllImsiList = MainActivity.getInstance().getImsiList();
                currentKey = s.toString();
                mImsiList.clear();
                if (!TextUtils.isEmpty(s)){
                    for (ImsiBean bean : mAllImsiList){
                        if (bean.getImsi().contains(currentKey)) mImsiList.add(bean);
                    }
                } else mImsiList.addAll(mAllImsiList);
                mImsiAdapter.resetShowData();
            }
        });

        root.findViewById(R.id.clear).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clear();
            }
        });
        // 列表
        RecyclerView rv_imsi_list = root.findViewById(R.id.rv_imsi_list);
        mImsiAdapter = new ImsiAdapter(mContext, mImsiList);
        mImsiAdapter.setOnItemClickListener(new BeanClickListener() {
            @Override
            public void onItemClickListener(View view, ImsiBean bean) {
                if (device != null && device.getWorkState() == GnbBean.State.TRACE) showChangeImsiDialog(view, bean);
            }
        });
        rv_imsi_list.setLayoutManager(new LinearLayoutManager(mContext));
        rv_imsi_list.setAdapter(mImsiAdapter);

        // 创建一个数据集合
        List<String> dataList = new ArrayList<>();
        dataList.add(mContext.getString(R.string.rsrp_sort));
        dataList.add(mContext.getString(R.string.count_sort));
        dataList.add(mContext.getString(R.string.time_sort));

        // 创建一个适配器对象
        final Spinner sp_sort = root.findViewById(R.id.sp_sort);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(mContext, android.R.layout.simple_spinner_item, dataList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_sort.setAdapter(adapter);
        sp_sort.setSelection(mImsiAdapter.getSortMode(), true);
        sp_sort.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                mImsiAdapter.setSortMode(sp_sort.getSelectedItemPosition());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        TextView tv_bulk_operation = root.findViewById(R.id.tv_bulk_operation);
        tv_bulk_operation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BulkOperationDialog dialog = new BulkOperationDialog(mContext, mImsiAdapter.getSortMode());
                dialog.show();
            }
        });
        if (ZApplication.getInstance().isTrace) {
            sp_sort.setVisibility(View.GONE);
            tv_bulk_operation.setVisibility(View.GONE);
        }else if (ZApplication.getInstance().isCatch) tv_bulk_operation.setVisibility(View.GONE);
    }

    private void showChangeImsiDialog(View v, ImsiBean bean) {
        if (ZApplication.getInstance().isTrace){
            Dialog dialog = MainActivity.getInstance().createDialog(false);
            View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_confirm, null);
            TextView tv_title = view.findViewById(R.id.tv_title);
            tv_title.setText(getString(R.string.change_imsi));
            TextView tv_msg = view.findViewById(R.id.tv_msg);
            tv_msg.setText(getString(R.string.change_imsi_tip));

            final TextView btn_ok = view.findViewById(R.id.btn_ok);
            btn_ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MainActivity.getInstance().checkAndChangeImsi(bean.getImsi());
                    MainActivity.getInstance().closeDialog(dialog);
                }
            });
            final TextView btn_cancel = view.findViewById(R.id.btn_cancel);
            btn_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MainActivity.getInstance().closeDialog(dialog);
                }
            });
            MainActivity.getInstance().showDialog(dialog, view, false);
        }else {
            View view = LayoutInflater.from(mContext).inflate(R.layout.popup_imsi_click_menu, null);
            final PopupWindow popupWindow = new PopupWindow(view, Util.dp2px(mContext, 16 * 8), Util.dp2px(mContext, 40 * (ZApplication.getInstance().isCatch ? 2 : 3)), true);
            TextView tv_go_up = view.findViewById(R.id.tv_go_up);
            TextView tv_add_list = view.findViewById(R.id.tv_add_list);
            if (ZApplication.getInstance().isCatch){
                boolean isInWarning = MainActivity.getInstance().isInWarningImsiList(bean.getImsi());
                tv_go_up.setText(isInWarning ? getString(R.string.remove_warning) : getString(R.string.add_warning));
                tv_add_list.setVisibility(View.GONE);
                tv_go_up.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popupWindow.dismiss();
                        MainActivity.getInstance().deleteOrAddWarning(bean);
                    }
                });
            }else {
                boolean setNull = MainActivity.getInstance().mImsiBean != null && MainActivity.getInstance().mImsiBean.getImsi().equals(bean.getImsi());
                tv_go_up.setText(getString(setNull ? R.string.cancel_target : R.string.set_target));
                tv_go_up.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popupWindow.dismiss();
                        MainActivity.getInstance().setConfigInfo(setNull ? null : bean);
                        mImsiAdapter.updateImsi(bean, setNull);
                    }
                });

                boolean inBlackList = MainActivity.getInstance().isInBlackList(bean.getImsi());
                tv_add_list.setText(inBlackList ? getString(R.string.remove_white_list) : getString(R.string.add_white_list));
                tv_add_list.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        popupWindow.dismiss();

                        if (inBlackList){
                            MainActivity.getInstance().deleteOrAdd(bean);
                            MainActivity.getInstance().sendBlackListToDev();
                        }else showBlackListCfgDialog(bean);
                    }
                });
            }

            TextView tv_edit_nodes = view.findViewById(R.id.tv_edit_nodes);
            tv_edit_nodes.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    popupWindow.dismiss();
                    showEditNodesDialog(bean);
                }
            });

            popupWindow.setFocusable(true);
            popupWindow.setOutsideTouchable(true);

            Drawable drawable = ContextCompat.getDrawable(mContext, R.drawable.bg_popup);
            popupWindow.setBackgroundDrawable(drawable);

            popupWindow.showAsDropDown(v, 80, 0);
        }
    }

    private void showEditNodesDialog(final ImsiBean bean) {

        Dialog dialog = MainActivity.getInstance().createDialog(false);

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_edit_nodes, null);

        final TextView btn_ok = view.findViewById(R.id.btn_ok);
        final TextView btn_cancel = view.findViewById(R.id.btn_cancel);
        TextView back = view.findViewById(R.id.back);
        final EditText ed_nodes = view.findViewById(R.id.ed_nodes);
        ed_nodes.setText(bean.getNotes());
        if (bean.getNotes().isEmpty()) {
            btn_ok.setText(R.string.add);
            btn_cancel.setText(R.string.cancel);
            btn_cancel.setTextColor(Color.parseColor("#666666"));
            back.setVisibility(View.GONE);
        } else {
            btn_ok.setText(R.string.confirm_modify);
            btn_cancel.setText(R.string.delete);
            btn_cancel.setTextColor(Color.RED);
            back.setVisibility(View.VISIBLE);
        }

        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String nodes = ed_nodes.getText().toString();
                for (ImsiBean item : MainActivity.getInstance().getImsiList()){
                    if (item.getImsi().equals(bean.getImsi())) {
                        item.setNotes(nodes);
                        MainActivity.getInstance().notesMap.put(item.getImsi(), nodes);
                        PrefUtil.build().putString("imsi_notes", GsonUtil.strMapToJson(MainActivity.getInstance().notesMap));
                        break;
                    }
                }
                refreshListView();
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btn_cancel.getText().toString().equals(getString(R.string.delete))) {
                    new AlertDialog.Builder(mContext)
                            .setTitle(R.string.delete_tip_title)
                            .setMessage(R.string.delete_tip)
                            .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int type) {
                                    for (ImsiBean item : MainActivity.getInstance().getImsiList()){
                                        if (item.getImsi().equals(bean.getImsi())) {
                                            item.setNotes("");
                                            MainActivity.getInstance().notesMap.remove(item.getImsi());
                                            PrefUtil.build().putString("imsi_notes", GsonUtil.strMapToJson(MainActivity.getInstance().notesMap));
                                            break;
                                        }
                                    }
                                    refreshListView();
                                    MainActivity.getInstance().closeDialog(dialog);
                                }
                            })
                            .setNegativeButton(R.string.cancel, null)
                            .show();
                } else MainActivity.getInstance().closeDialog(dialog);
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, false);
    }

    private void showBlackListCfgDialog(ImsiBean bean) {

        Dialog dialog = MainActivity.getInstance().createDialog(false);

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_black_list_cfg, null);

        TextView tv_black_cfg_title = view.findViewById(R.id.tv_black_cfg_title);

        final TextView btn_ok = view.findViewById(R.id.btn_ok);
        final TextView btn_cancel = view.findViewById(R.id.btn_cancel);
        TextView back = view.findViewById(R.id.back);
        final EditText ed_imsi_name = view.findViewById(R.id.ed_imsi_name);
        final AutoCompleteTextView actv_imsi = view.findViewById(R.id.actv_imsi);
        tv_black_cfg_title.setText(R.string.add_black_title);
        btn_ok.setText(R.string.add);
        btn_cancel.setText(R.string.cancel);
        btn_cancel.setTextColor(Color.parseColor("#666666"));
        back.setVisibility(View.GONE);
        ed_imsi_name.setText(bean.getImsi().substring(11));
        actv_imsi.setText(bean.getImsi());

        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String imsi_name = ed_imsi_name.getText().toString();
                String imsi = actv_imsi.getText().toString();
                if (imsi_name.isEmpty() || imsi.isEmpty()) {
                    MainActivity.getInstance().showToast(getString(R.string.data_empty_tip));
                    return;
                }
                if (imsi.length() != 15) {
                    MainActivity.getInstance().showToast(getString(R.string.imsi_err_tip));
                    return;
                }

                MyUeidBean bean;
                boolean canAdd = true;
                for (MyUeidBean bean1 : MainActivity.getInstance().getBlackList()) {
                    if (bean1.getUeidBean().getImsi().equals(imsi)) {
                        canAdd = false;
                        break;
                    }
                }
                if (canAdd) {
                    bean = new MyUeidBean(imsi_name, new UeidBean(imsi, ""), false, false);
                    MainActivity.getInstance().getBlackList().add(bean);
                    MainActivity.getInstance().sendBlackListToDev();
                } else {
                    MainActivity.getInstance().showToast(getString(R.string.imsi_repeat_tip));
                    return;
                }

                PrefUtil.build().putString("black_list", GsonUtil.createJsonString(MainActivity.getInstance().getBlackList()));
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.getInstance().closeDialog(dialog);
            }
        });
        MainActivity.getInstance().showDialog(dialog, view, false);
    }

    public void resetShowData(){
        if (mImsiAdapter != null) mImsiAdapter.resetShowData(); // 刷新视图
    }

    public void clear() {
        if (!mImsiList.isEmpty()) {
            new AlertDialog.Builder(mContext)
                    .setTitle(R.string.clear_title)
                    .setMessage(R.string.clear_tip)
                    .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            mImsiList.clear();
                            MainActivity.getInstance().getImsiList().clear();
                            mImsiAdapter.resetShowData();
                            MainActivity.getInstance().saveDataList();
                        }
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .show();
        }else if (this.isAdded()) MainActivity.getInstance().showToast(getString(R.string.list_empty));
    }
}